from libavg import avg, ui
from libavg.ui.button import TouchButton
import Constants
import math
import xml.dom.minidom as dom
import os.path
from string import strip

class LevelEditor(avg.DivNode):
    
    __SIZE_BGR = avg.Point2D(250, Constants.RESOLUTION.y) 

    def __init__(self, parent, game, **kwargs):
        super(LevelEditor, self).__init__(**kwargs)
        
        if parent:
            parent.appendChild(self)
            
        self.size = Constants.RESOLUTION 

        self.__game = game
        self.__bricks = []
        self.__bgr = 1
        self.__imgBgr = avg.ImageNode(href = "resources/textures/level/bgr_"+self.__bgr.__str__()+".png", parent=self, size=self.size)   
        self.__menuBgr = avg.RectNode(parent=self, size=self.__SIZE_BGR, color = "000000", fillcolor="000000", fillopacity=1)
        
        self.deselectRecognizer = ui.TapRecognizer(node=self.__imgBgr,
                                                   detectedHandler=self.__bgrTap
                                                   )     
       
        self.__cannonSpace1 = avg.RectNode(parent=self, size=(175, 126), color = "FF0000", strokewidth = 2, pos=(Constants.RESOLUTION.x/2-88, 0))
        self.__cannonSpace2 = avg.RectNode(parent=self, size=(175, 126), color = "FF0000", strokewidth = 2, pos=(Constants.RESOLUTION.x/2-88, Constants.RESOLUTION.y - 126))
       
        avg.LineNode(parent=self, pos1=(Constants.RESOLUTION.x/4, 0), pos2=(Constants.RESOLUTION.x/4,Constants.RESOLUTION.y), color="FFFFFF")
        avg.LineNode(parent=self, pos1=(Constants.RESOLUTION.x-(Constants.RESOLUTION.x/4), 0), pos2=(Constants.RESOLUTION.x-(Constants.RESOLUTION.x/4),Constants.RESOLUTION.y), color="FFFFFF")
        
        #Object selector
        self.__objSelector = ObjectSelector(parent=self)
        self.curBrick = None
        self.isSaved = True
        self.players = 1
        self.level = 1
        self.__updateLevelCount()
        self.__msg = avg.WordsNode(parent=self, pos=(Constants.RESOLUTION.x/2, Constants.RESOLUTION.y/2 - 35), text="SAVED !", font="Arial", variant="Bold", fontsize=70.0, alignment="center")
        self.__msg.opacity = 0
        self.__msg.active = False
        self.__isMsgShown = False
        
        self.__objPropertiesMenu = ObjectPropertiesMenu(parent=self)
        
        self.__bgrSelector = BackgroundSelector(parent=self)
        
        self.__levelSelector = LevelSelector(parent=self)
        
        self.__loadLevel(self.level)
        
        self.__closeBtn = TouchButton (
                parent = self,
                pos = (250 + 5, Constants.RESOLUTION.y - 50 - 8),
                size = (50, 50),
                upNode = avg.ImageNode(href = "resources/textures/menu/btn_exit.png", size=(50, 50)),
                downNode = avg.ImageNode(href = "resources/textures/menu/btn_exit_d.png", size=(50, 50)),
                clickHandler = lambda: self.__game.showMenu()) 
        
    def __msgTimeout(self):
        avg.Player.get().clearInterval(self.__msgTimer)
        self.__msg.opacity = 1
        self.__msg.text = ""
        self.__isMsgShown = False
        self.__msg.active = False
        
    def showMsg(self, val):
        self.__msg.active = True
        self.__msg.text = val
        self.__msg.opacity = 1
        if self.__isMsgShown == True:
                avg.Player.get().clearInterval(self.__msgTimer)
        self.__isMsgShown = True
        self.__msgTimer = avg.Player.get().setInterval(1200, self.__msgTimeout) 

    def __bgrTap(self, event):
        if self.curBrick is not None:
            self.curBrick.deselect()
         
    def __updateLevelCount(self):
        if self.players == 1:
            in_directory = "resources/levels/sp"
        elif self.players == 2:
            in_directory = "resources/levels/mp"
        else:
            return
                    
        joiner = (in_directory + os.path.sep).__add__
        self.levelCount = sum(
        os.path.isfile(filename)
        for filename
        in map(joiner, os.listdir(in_directory))
        )

    def reset(self):
        if self.isSaved == False:
            self.isSaved = True
        self.__loadLevel(self.level)

    def getBgr(self):
        return self.__bgr

    # save all created levels
    def save(self):
        
        if self.players == 1 and self.level < 5:
            self.showMsg("level " + "SP-" + self.level.__str__() + " is ReadOnly")
            return

        bricks = self.xml.getElementsByTagName("brick")
        
        #Avoid stupid empty levels
        if self.__bricks.__len__() == 0:
            self.addBrick()
            
        for br in bricks:
            br.parentNode.removeChild(br)
        
        levels = self.xml.getElementsByTagName("level")
        for l in levels:
            l.setAttribute("bgr", self.__bgr.__str__())
            l.setAttribute("customized", "1")
            l.setAttribute("points", "0")
            l.setAttribute("finished", "0")
        
        for b in self.__bricks:
            newtag = self.xml.createElement("brick")
            newtag.setAttribute("x", b.pos.x.__str__())
            newtag.setAttribute("y", b.pos.y.__str__())
            newtag.setAttribute("height", b.size.y.__str__())
            newtag.setAttribute("width", b.size.x.__str__())
            newtag.setAttribute("life", b.hardness.__str__())
            newtag.setAttribute("angle", b.rotation.__str__())
            self.xml.documentElement.appendChild(newtag)
        
        xmlstr = self.xml.toprettyxml(encoding='utf-8')
        
        if self.players == 1:
            outFile = "resources/levels/sp/"+self.level.__str__()+".xml"
        elif self.players == 2:
            outFile = "resources/levels/mp/"+self.level.__str__()+".xml"
        else:
            return

        outTmp = "resources/levels/tmp.xml"
        
        f = open(outTmp, 'w')
        f.write(xmlstr)
        f.close()
        
        #The following seems to be strange but we want to keep xml structures clean as well and prettyxml in minidom
        #sucks a lot for this issue. Therefore we remove empty lines in a second I/O run to avoid fixing minidom
        #library on the multitouch table's python installation

        w = open(outFile,'w')
        ff = open(outTmp, 'r')
        for line in ff.readlines():
            if strip(line) == "":
                continue
            else: 
                w.write(line)
        w.close()
        ff.close()
        
        ###End of dirty prettyxml hack
        
        self.showMsg("Saved level " + ("SP-" if self.players == 1 else "MP-") + self.level.__str__() )
        self.isSaved = True
    
    def changeBgr(self, bgrVal):
        self.__bgr = bgrVal
        self.__imgBgr.href = "resources/textures/level/bgr_"+self.__bgr.__str__()+".png"
        self.isSaved = False
        self.__bgrSelector.updateStr()
        
    def changeLevel(self, levelVal):
        #Avoid stupid empty levels
        if self.__bricks.__len__() == 0:
            self.addBrick()
        
        if self.isSaved == False:
            self.save()
        
        self.__updateLevelCount()
        if (levelVal) > self.levelCount:
            self.newLevel(levelVal)
        elif (levelVal) > 0:
            self.__loadLevel(levelVal)
            
        return self.level
    
    def switchLevelMode(self, newVal):
        if self.isSaved == False:
            self.save()
            
        self.players = newVal
        return self.changeLevel(1) 

    def __loadLevel(self, lid):
        self.level = lid
        
        for b in self.__bricks:
            b.destory()
            b = None
        self.__bricks = []
        
        if self.players == 1:
            in_directory = "resources/levels/sp/"+self.level.__str__()+".xml"
        elif self.players == 2:
            in_directory = "resources/levels/mp/"+self.level.__str__()+".xml"
        else:
            return
        self.xml = dom.parse(in_directory)
        
        leveltag = self.xml.getElementsByTagName("level")[0]
        self.changeBgr((int)(leveltag.getAttribute("bgr")) ) 
        bricks = self.xml.getElementsByTagName("brick")
        
        tmpBrick = None
        for brick in bricks:
            x = eval("float("+brick.getAttribute("x")+")")
            y = eval("float("+brick.getAttribute("y")+")")
            width = eval("float("+brick.getAttribute("width")+")")
            height = eval("float("+brick.getAttribute("height")+")")
            life = eval("int("+brick.getAttribute("life")+")")
            angle = eval("int("+brick.getAttribute("angle")+")")
            tmpBrick = Brick(parent=self, size=(width, height), hardness=life, position=(x, y), angleIn=angle)
            self.__bricks.append(tmpBrick)
        
        if tmpBrick is not None:
            self.curBrick = tmpBrick
            self.curBrick.select()
        
        self.isSaved = True
        self.reorderChild(self.__msg, self.getNumChildren( )- 1)
    
    def newLevel(self, lid):
        self.level = lid
        
        if self.players == 1:
            in_directory = "resources/levels/empty_sp.xml"
        elif self.players == 2:
            in_directory = "resources/levels/empty_mp.xml"
        else:
            return
        
        xml = dom.parse(in_directory)
        xmlstr = xml.toxml('utf-8')
        
        if self.players == 1:
            outFile = "resources/levels/sp/"+self.level.__str__()+".xml"
        elif self.players == 2:
            outFile = "resources/levels/mp/"+self.level.__str__()+".xml"
        else:
            return
        
        f = open(outFile, 'w')
        f.write(xmlstr)
        f.close()
        
        self.__loadLevel(self.level)
    
    def addBrick(self):
        for b in self.__bricks:
            b.deselect()

        self.curBrick = Brick(parent=self)
        self.__bricks.append(self.curBrick)
        self.curBrick.select()
        
        self.isSaved = False
        
    def copyBrick(self):
        if self.curBrick is None:
            return
        
        for b in self.__bricks:
            b.deselect()

        nBrick = Brick(parent=self.curBrick.parentNode, size=self.curBrick.size, hardness=self.curBrick.hardness, position=(self.curBrick.pos.x + 3, self.curBrick.pos.y), angleIn=self.curBrick.rotation)
        self.curBrick = nBrick
        self.__bricks.append(self.curBrick)
        self.curBrick.select()
        
        self.isSaved = False
        
    def removeBrick(self):
        if self.curBrick is None:
            return
        
        self.__bricks.remove(self.curBrick)
        self.curBrick.destory()
        self.curBrick = None
        self.curBrick = None if self.__bricks.__len__() == 0 else self.__bricks[self.__bricks.__len__()-1]

        if self.curBrick is not None:
            self.curBrick.select()
        
        self.isSaved = False
    
    def changeHardness(self, val):
        if self.curBrick is not None:
            self.curBrick.setHardness(val)
        
        self.isSaved = False
            
    def changeRotation(self, val):
        if self.curBrick is not None:
            if val == 0:
                self.curBrick.rotateLeft()
            else:
                self.curBrick.rotateRight()
                
        self.isSaved = False
            
    def changeSize(self, mode, val):
        if self.curBrick is not None:
            if val == 0:
                self.curBrick.shrink(mode)
            else:
                self.curBrick.increase(mode)
                
        self.isSaved = False
        
    def changeBrick(self, brick):
        for b in self.__bricks:
            b.deselect()
            
        self.curBrick = brick
        self.curBrick.select()
 
class BackgroundSelector(avg.DivNode):
       
    __BTN_SIZE = avg.Point2D(80, 55)  
    value = 1   
       
    def __init__(self, parent, **kwargs):
        super(BackgroundSelector, self).__init__(**kwargs)
        
        if parent:
            parent.appendChild(self)
            self.__parentNode = parent
            
        self.size = (250,110)
        self.pos = (0, 530)
        
        avg.WordsNode(parent=self, pos=(13, 20), text="Background:", font="Arial", variant="Bold", fontsize=20.0, alignment="left")
        
        self.__lastBtn = TouchButton(
                parent = self,
                pos = (20, 45),
                size = self.__BTN_SIZE,
                upNode = avg.ImageNode(size=self.__BTN_SIZE, href = "resources/textures/editor/btn_last.png"),
                downNode = avg.ImageNode(size=self.__BTN_SIZE, href = "resources/textures/editor/btn_last_d.png"),
                clickHandler = self.lastBgr)

        self.__levelStr = avg.WordsNode(parent=self, pos=(240, 20), text=self.value.__str__(), font="Arial", variant="Bold", fontsize=20.0, alignment="right")
        
        self.nextBtn = TouchButton(
                parent = self,
                pos = (135, 45),
                size = self.__BTN_SIZE,
                upNode = avg.ImageNode(href = "resources/textures/editor/btn_next.png", size=self.__BTN_SIZE),
                downNode = avg.ImageNode(href = "resources/textures/editor/btn_next_d.png", size=self.__BTN_SIZE),
                clickHandler = self.nextBgr) 
    
    def __handleBgrChange(self, newVal):
        if (self.value + newVal) < 1 or (self.value + newVal) > 9:
            return
       
        self.value = self.value + newVal
        self.__levelStr.text = self.value.__str__()
        self.__parentNode.changeBgr(self.value)     
        
        
    def nextBgr(self):
        self.__handleBgrChange(1)
        
    def lastBgr(self):
        self.__handleBgrChange(-1)
        
    def updateStr(self):
        self.value = self.__parentNode.getBgr()
        self.__levelStr.text = self.value.__str__()

class LevelSelector(avg.DivNode):
       
    __BTN_SIZE = avg.Point2D(80, 55) 
    __BTN_SAVE_SIZE = avg.Point2D(50, 40) 
    value = 1
       
    def __init__(self, parent, **kwargs):
        super(LevelSelector, self).__init__(**kwargs)
        
        if parent:
            parent.appendChild(self)
            self.__parentNode = parent
            
        self.size = (250, 165)
        self.pos = (0, 638)
        
        avg.WordsNode(parent=self, pos=(13, 20), text="Level:", font="Arial", variant="Bold", fontsize=20.0, alignment="left")
        
        self.__lastBtn = TouchButton(
                parent = self,
                pos = (20, 45),
                size = self.__BTN_SIZE,
                upNode = avg.ImageNode(size=self.__BTN_SIZE, href = "resources/textures/editor/btn_last.png"),
                downNode = avg.ImageNode(size=self.__BTN_SIZE, href = "resources/textures/editor/btn_last_d.png"),
                clickHandler = lambda: self.handleLevelChange(-1))

        self.__levelStr = avg.WordsNode(parent=self, pos=(240, 20), text=("(SP) " if self.__parentNode.players == 1 else "(MP) ") + self.value.__str__(), font="Arial", variant="Bold", fontsize=20.0, alignment="right")
        
        self.__nextBtn = TouchButton(
                parent = self,
                pos = (135, 45),
                size = self.__BTN_SIZE,
                upNode = avg.ImageNode(href = "resources/textures/editor/btn_next.png", size=self.__BTN_SIZE),
                downNode = avg.ImageNode(href = "resources/textures/editor/btn_next_d.png", size=self.__BTN_SIZE),
                clickHandler = lambda: self.handleLevelChange(1)) 
        
        self.__saveBtn = TouchButton(
                parent = self,
                pos = (185, 110),
                size = self.__BTN_SAVE_SIZE,
                upNode = avg.ImageNode(href = "resources/textures/editor/btn_save.png", size=self.__BTN_SAVE_SIZE),
                downNode = avg.ImageNode(href = "resources/textures/editor/btn_save_d.png", size=self.__BTN_SAVE_SIZE),
                clickHandler = self.saveLevel)
        
        self.__resetBtn = TouchButton(
                parent = self,
                pos = (135, 110),
                size = self.__BTN_SAVE_SIZE,
                upNode = avg.ImageNode(href = "resources/textures/editor/btn_reset.png", size=self.__BTN_SAVE_SIZE),
                downNode = avg.ImageNode(href = "resources/textures/editor/btn_reset_d.png", size=self.__BTN_SAVE_SIZE),
                clickHandler = lambda: self.__parentNode.reset())
        
        self.__spBtn = TouchButton(
                parent = self,
                pos = (15, 110),
                size = self.__BTN_SAVE_SIZE,
                upNode = avg.ImageNode(href = "resources/textures/editor/btn_sp.png", size=self.__BTN_SAVE_SIZE),
                downNode = avg.ImageNode(href = "resources/textures/editor/btn_sp_d.png", size=self.__BTN_SAVE_SIZE),
                clickHandler = lambda: self.handleChangePlayers(1))
        
        self.__mpBtn = TouchButton(
                parent = self,
                pos = (65, 110),
                size = self.__BTN_SAVE_SIZE,
                upNode = avg.ImageNode(href = "resources/textures/editor/btn_mp.png", size=self.__BTN_SAVE_SIZE),
                downNode = avg.ImageNode(href = "resources/textures/editor/btn_mp_d.png", size=self.__BTN_SAVE_SIZE),
                clickHandler = lambda: self.handleChangePlayers(2) )

    def saveLevel(self):
        if self.__parentNode.isSaved == False:
            self.__parentNode.save()   
            
    def handleChangePlayers(self, newVal):
        if self.__parentNode.players == newVal:
            return
        
        self.value = self.__parentNode.switchLevelMode(newVal)
        self.__levelStr.text = ("(SP) " if self.__parentNode.players == 1 else "(MP) ") + self.value.__str__()
    
    def handleLevelChange(self, newVal):
        if (self.value + newVal) < 1:
            return
       
        self.value = self.__parentNode.changeLevel(self.value + newVal) 
        self.__levelStr.text = ("(SP) " if self.__parentNode.players == 1 else "(MP) ") + self.value.__str__()
        
class ObjectSelector(avg.DivNode):
       
    __BTN_SIZE = avg.Point2D(70,110)  
       
    def __init__(self, parent, **kwargs):
        super(ObjectSelector, self).__init__(**kwargs)
        
        if parent:
            parent.appendChild(self)
            self.parentNode = parent
            
        self.size = (250, 140)
        
        self.__addBrickBtn = TouchButton(
                parent = self,
                pos = (15, 30),
                size = self.__BTN_SIZE,
                upNode = avg.ImageNode(href = "resources/textures/editor/btn_brick.png"),
                downNode = avg.ImageNode(href = "resources/textures/editor/btn_brick_d.png"),
                clickHandler = self.parentNode.addBrick)
        
        self.__copyBrickBtn = TouchButton(
                parent = self,
                pos = (90, 33),
                size = self.__BTN_SIZE,
                upNode = avg.ImageNode(href = "resources/textures/editor/btn_brick_copy.png"),
                downNode = avg.ImageNode(href = "resources/textures/editor/btn_brick_copy_d.png"),
                clickHandler = self.parentNode.copyBrick)
        
        self.__remBrickBtn = TouchButton(
                parent = self,
                pos = (165, 33),
                size = self.__BTN_SIZE,
                upNode = avg.ImageNode(href = "resources/textures/editor/btn_brick_remove.png"),
                downNode = avg.ImageNode(href = "resources/textures/editor/btn_brick_remove_d.png"),
                clickHandler = self.parentNode.removeBrick)
        
class ObjectPropertiesMenu(avg.DivNode):
       
    def __init__(self, parent, **kwargs):
        super(ObjectPropertiesMenu, self).__init__(**kwargs)
        
        if parent:
            parent.appendChild(self)
            self.parentNode = parent
            
        self.size = (250, 415)   
        self.pos = (0, 130)
            
        avg.WordsNode(parent=self, pos=(13, 20), text="Hardness:", font="Arial", variant="Bold", fontsize=20.0, alignment="left")    
            
        self.__btns_hardness = []
        self.__btns_hardness.append(HardnessSelectionButton(parent=self, value=1, pos=(13, 50)))
        self.__btns_hardness.append(HardnessSelectionButton(parent=self, value=2, pos=(58, 50)))
        self.__btns_hardness.append(HardnessSelectionButton(parent=self, value=3, pos=(103, 50)))
        self.__btns_hardness.append(HardnessSelectionButton(parent=self, value=4, pos=(148, 50)))
        self.__btns_hardness.append(HardnessSelectionButton(parent=self, value=5, pos=(193, 50)))
        
        avg.WordsNode(parent=self, pos=(13, 100), text="Rotation:", font="Arial", variant="Bold", fontsize=20.0, alignment="left")
    
        RotationSelectionButton(parent=self, value=0, pos=(45, 130))
        RotationSelectionButton(parent=self, value=1, pos=(145, 130))
        
        avg.WordsNode(parent=self, pos=(13, 210), text="Size:", font="Arial", variant="Bold", fontsize=20.0, alignment="left")
    
        SizeSelectionButton(parent=self, mode=0, value=0, pos=(20, 240))
        avg.ImageNode(href = "resources/textures/editor/img_size_width.png", parent = self, size = (50, 30), pos=(105, 255))
        SizeSelectionButton(parent=self, mode=0, value=1, pos=(180, 240))
        
        SizeSelectionButton(parent=self, mode=1, value=0, pos=(20, 310))
        avg.ImageNode(href = "resources/textures/editor/img_size_height.png", parent = self, size = (35, 35), pos=(112, 323))
        SizeSelectionButton(parent=self, mode=1, value=1, pos=(180, 310))
        
    def changeHardness(self, val):
        self.parentNode.changeHardness(val)
    
    def changeRotation(self, val):
        self.parentNode.changeRotation(val)
    
    def changeSize(self, mode, val):
        self.parentNode.changeSize(mode, val)

class HardnessSelectionButton(avg.DivNode):
    
    __SIZE_DEFAULT = avg.Point2D(40,40)
    value = -1
    
    def __init__(self, parent, value, **kwargs):
        super(HardnessSelectionButton, self).__init__(**kwargs)
        
        if parent:
            parent.appendChild(self)
           
        self.size = self.__SIZE_DEFAULT
        self.__btn = TouchButton(
                parent = parent,
                pos = self.pos,
                size = self.__SIZE_DEFAULT,
                upNode = avg.ImageNode(size = self.__SIZE_DEFAULT, href = "resources/textures/editor/btn_"+value.__str__()+".png"),
                downNode = avg.ImageNode(size = self.__SIZE_DEFAULT, href = "resources/textures/editor/btn_"+value.__str__()+"_d.png"),
                clickHandler = lambda: parent.changeHardness(value))
        
class RotationSelectionButton(avg.DivNode):
    
    __SIZE_DEFAULT = avg.Point2D(77,66)
    __VALUE = 0
    
    def __init__(self, parent, value, **kwargs):
        super(RotationSelectionButton, self).__init__(**kwargs)
        
        if parent:
            parent.appendChild(self)
           
        self.size = self.__SIZE_DEFAULT
        if value == 0:
            self.__btn = TouchButton(
                    parent = self,
                    size = self.__SIZE_DEFAULT,
                    upNode = avg.ImageNode(size = self.__SIZE_DEFAULT, href = "resources/textures/editor/btn_rot_left.png"),
                    downNode = avg.ImageNode(size = self.__SIZE_DEFAULT, href = "resources/textures/editor/btn_rot_left_d.png"),
                    clickHandler = lambda: parent.changeRotation(value))
        else:
            self.__btn = TouchButton(
                    parent = self,
                    size = self.__SIZE_DEFAULT,
                    upNode = avg.ImageNode(size = self.__SIZE_DEFAULT, href = "resources/textures/editor/btn_rot_right.png"),
                    downNode = avg.ImageNode(size = self.__SIZE_DEFAULT, href = "resources/textures/editor/btn_rot_right_d.png"),
                    clickHandler = lambda: parent.changeRotation(value))
        
class SizeSelectionButton(avg.DivNode):
    
    __SIZE_DEFAULT = avg.Point2D(61,61)
    __VALUE = 0
    
    def __init__(self, parent, mode, value, **kwargs):
        super(SizeSelectionButton, self).__init__(**kwargs)
        
        if parent:
            parent.appendChild(self)
            self.parentNode = parent
           
        self.size = self.__SIZE_DEFAULT
        if value == 0:
            self.__btn = TouchButton(
                    parent = self,
                    size = self.__SIZE_DEFAULT,
                    upNode = avg.ImageNode(size = self.__SIZE_DEFAULT, href = "resources/textures/editor/btn_shrink.png"),
                    downNode = avg.ImageNode(size = self.__SIZE_DEFAULT, href = "resources/textures/editor/btn_shrink_d.png"),
                    clickHandler = lambda: parent.changeSize(mode, value))
        else:
            self.__btn = TouchButton(
                    parent = self,
                    size = self.__SIZE_DEFAULT,
                    upNode = avg.ImageNode(size = self.__SIZE_DEFAULT, href = "resources/textures/editor/btn_increase.png"),
                    downNode = avg.ImageNode(size = self.__SIZE_DEFAULT, href = "resources/textures/editor/btn_increase_d.png"),
                    clickHandler = lambda: parent.changeSize(mode, value))
    
class Brick(avg.DivNode):
    
    __SIZE_DEFAULT = avg.Point2D(15, 40)
    __SIZE_NEXT = 5
    hardness = 1
    rotation = 0
           
    def __init__(self, parent, size=None, hardness=None, position=None, angleIn=None, **kwargs):
        super(Brick, self).__init__(**kwargs)
        
        if parent:
            parent.appendChild(self)
            self.parentNode = parent
            
        if hardness is not None:
            self.hardness = hardness
        
        if size is not None:
            self.size = size
        else:
            self.size = self.__SIZE_DEFAULT
            
        if angleIn is not None:
            self.rotation = angleIn
            self.angle = angleIn * (math.pi / 4)
        
        if position is not None:
            self.pos = position
        else:
            self.pos = (Constants.RESOLUTION.x/2 - self.__SIZE_DEFAULT.x/2, Constants.RESOLUTION.y/2 - self.__SIZE_DEFAULT.y/2) 
        
        self.__tex = avg.ImageNode(parent=self, size=self.size, gamma = (1.0, 1.0, 1.0))
        self.__tex.setBitmap(avg.SVG('resources/textures/brick/bgr.svg', False).renderElement('Layer1'))
        
        self.__rect = avg.RectNode(parent=self, size=(self.size.x, self.size.y), color = "FFFFFF")
        self.__rect.strokewidth = 1 
        self.__rect.active = False

        self.__canMove = True
        
        self.__transformRecognizer = ui.TransformRecognizer(
                eventNode=self, 
                detectedHandler=self.__onDTap,
                moveHandler=self.__onMove,
                upHandler=self.__onUp,
                friction=1
        )
        
        self.isSelected = False
        self.updateColors()
    
    def __onUp(self, event):
        self.updateColors()
    
    def __onMove(self, transform):
        if self.__canMove == True:
            self.__rect.active = False
            transform.scale = 1
            transform.rot = 0
            transform.moveNode(self)
            self.__tex.intensity = (1.0, 1.0, 1.0)
            self.parentNode.isSaved = False
            
    def __onDTap(self, event):
        self.select()
        self.parentNode.changeBrick(self)
    
    def updateColors(self):
        if self.isSelected:
            self.__rect.active = True
        else:
            self.__rect.active = False
        self.__tex.intensity = Constants.BRICK_COLORS[(self.hardness-1) if (self.hardness-1) <= Constants.BRICK_COLORS.__len__() else Constants.BRICK_COLORS.__len__() - 1]
    
    def select(self):
        self.isSelected = True
        self.__canMove = True
        self.updateColors()
    
    def deselect(self):
        self.isSelected = False
        self.__canMove = False
        self.updateColors()
    
    def setHardness(self, val):
        self.hardness = val
        self.updateColors()
        
    def rotateLeft(self):
        self.rotation -= 1
        self.angle = self.angle - math.pi / 4
    
    def rotateRight(self):
        self.rotation += 1
        self.angle = self.angle + math.pi / 4
    
    def increase(self, mode):
        if mode == 0:
            self.size = (self.size.x + self.__SIZE_NEXT, self.size.y)
        else:
            self.size = (self.size.x, self.size.y + self.__SIZE_NEXT)
        self.__rect.size = self.size
        self.__tex.size = self.size
    
    def shrink(self, mode):
        if mode == 0:
            if (self.size.x - self.__SIZE_NEXT) >= self.__SIZE_DEFAULT.x:
                self.size = (self.size.x - self.__SIZE_NEXT, self.size.y)
        else:
            if (self.size.y - self.__SIZE_NEXT) >= self.__SIZE_DEFAULT.y:
                self.size = (self.size.x, self.size.y - self.__SIZE_NEXT)
        self.__rect.size = self.size
        self.__tex.size = self.size
    
    def destory(self):  
        self.__transformRecognizer.enable(False)
        self.__rect.unlink(True)
        self.__rect = None
        self.__tex.unlink(True)
        self.__tex = None
        self.unlink(True)
